/**
 * 提供 mapbox gl 颜色标记使用
 */

import gradientColor from '@/util/gradient-color'

/**
 * 生成连续型配置
 * @param min 最小值
 * @param max 最大值
 * @param step 步长
 * @param colors 颜色 例如：['#xxxxxx', '#xxxxxx', ?['#xxxxxx']], 2色 / 3色
 */
function generateSuccessiveColor(
  min: number,
  max: number,
  step: number,
  colors: string[]
): any[] {
  let calcStep: number = step
  if (step % 2 === 0) {
    calcStep = step + 1
  }
  let gradientColors: any
  if (colors.length === 3) {
    const ss: number = calcStep / 2
    const gradientColors1: string[] = gradientColor(colors[0], colors[1], ss)
    const gradientColors2: string[] = gradientColor(colors[1], colors[2], ss)
    gradientColors = [...gradientColors1, colors[1], ...gradientColors2]
  } else {
    gradientColors = gradientColor(colors[0], colors[1], step)
  }
  const averageValue: number = (max - min) / (calcStep - 1)
  const mapboxPaintAttributeValue: any = {}
  for (let i = 0; i < step - 1; i += 1) {
    const stepNumber: number = Math.floor((min + i * averageValue) * 100) / 100
    mapboxPaintAttributeValue[stepNumber] = gradientColors[i]
  }
  const result: any = {
    value: mapboxPaintAttributeValue,
  }
  return result
}

/**
 * 生成离散颜色
 * @param discreteValue  离散值
 * @param colors 颜色
 */
function generateDiscreteColor(discreteValue: any[], colors: string[]): any[] {
  const colorLengthMinusOne: number = colors.length - 1
  const mapboxPaintAttributeValue: any = {}
  discreteValue.forEach((value: string, index: number) => {
    mapboxPaintAttributeValue[value] = colors[index % colorLengthMinusOne]
  })
  const result: any = {
    value: mapboxPaintAttributeValue,
    lastColor: colors[colorLengthMinusOne],
  }
  return result
}

function generateColorGradient(type: 1 | 2, options: any) {
  let resultPaint: any = null
  if (type === 1) {
    const { min, max, step, colors } = options
    resultPaint = generateSuccessiveColor(min, max, step, colors)
  } else if (type === 2) {
    const { discreteValue, colors } = options
    resultPaint = generateDiscreteColor(discreteValue, colors)
  }
  return resultPaint
}

export default generateColorGradient
